Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.

题目大意:给定未排序数组和一个数val,在数组中移除与val相等的所有实例,返回新的长度len。要求空间复杂度O(1),数组元素顺序可以变,允许数组有剩余元素,前len个数不包含val即可。

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/8
 */
public class Solution {
    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) return 0;

        int len = nums.length;
        int k = 0;
        for (int i = 0; i < len; i++) {
            // 不相同时,更新nums[k] 和 k, 仅在k!=i时更新nums[k],避免不必要赋值
            if (nums[i] != val) {
                if (k != i) nums[k] = nums[i];
                ++k;
            }
        }
        return k;
    }
}
gzdaijie            updated 2016-05-08 13:08:22

results matching ""

    No results matching ""